#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        struct cmp {
            bool operator() (pair<int, int> a, pair<int, int> b) {
                return a.second > b.second;
            }
        };
        unordered_map<int, int> hash;
        for (auto& e : nums) ++hash[e];

        priority_queue<pair<int, int>, deque<pair<int, int>>, cmp> heap;
        auto it = hash.begin();
        int tmp = k;
        for (; tmp--; ++it) heap.push(*it);

        for (; it != hash.end(); ++it)
        {
            if (it->second > heap.top().second)
            {
                heap.pop();
                heap.push(*it);
            }
        }

        vector<int> res;
        while (k--)
        {
            res.push_back(heap.top().first);
            heap.pop();
        }
        return res;
    }
};